#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

#include "xml_parser.h"

#include "tinyxml.h"

TiXmlElement* FindElement( TiXmlElement* Root, const char* ElementName )
{
 TiXmlElement* pCurrentElement = Root;
 bool Done = false;
 while( pCurrentElement && !Done )
 {
  if( strcmp( pCurrentElement->Value() , ElementName ) == 0 )
  { Done = true; }
  else
  { pCurrentElement = pCurrentElement->NextSiblingElement(); }
 }
 return pCurrentElement;
}

TiXmlElement* FindChildElement( TiXmlElement* Root, const char* ElementName )
{
 TiXmlElement* pCurrentElement = Root->FirstChildElement();
 
 bool Done = false;
 while( pCurrentElement && !Done )
 {
  if( strcmp( pCurrentElement->Value() , ElementName ) == 0 )
  { Done = true; }
  else
  { pCurrentElement = pCurrentElement->NextSiblingElement(); }
 }
 return pCurrentElement;
}

TiXmlElement* FindNextChildElement( TiXmlElement* Root, TiXmlElement* LastHit, const char* ElementName )
{
 TiXmlElement* pCurrentElement = Root->FirstChildElement();
 
 bool Done = false;
 bool FoundPrevious = false;
 
 while( pCurrentElement && !Done  )
 {
  if( strcmp( pCurrentElement->Value() , ElementName ) == 0 &&
      pCurrentElement == LastHit )
  { FoundPrevious = true; }
 
  if( strcmp( pCurrentElement->Value() , ElementName ) == 0 &&
      pCurrentElement != LastHit && FoundPrevious )
  { Done = true; }
  else
  { pCurrentElement = pCurrentElement->NextSiblingElement(); }
 }
 return pCurrentElement;
}


int GetIntegerChildElement( TiXmlElement* Root, const char* ElementName )
{
 TiXmlElement* pElem = FindChildElement( Root, ElementName );
 if( !pElem )
 { return 0; }
 return atoi( pElem->GetText() );
}

double GetDoubleChildElement( TiXmlElement* Root, const char* ElementName )
{
 TiXmlElement* pElem = FindChildElement( Root, ElementName );
 if( !pElem )
 { return 0.0; }
 return strtod( pElem->GetText() , NULL );
}

char* GetStringChildElement( TiXmlElement* Root, const char* ElementName )
{
 char* Output = NULL;
 TiXmlElement* pElem = FindChildElement( Root, ElementName );
 
 if( !pElem )
 {
  Output = new char [1];
  Output[0] = '\0';

  return Output;
 }
 int Length = 0; 
 if( pElem->GetText() )
 { Length = strlen( pElem->GetText() ); }
 
// Output = new char [strlen( pElem->GetText() )+1];
 Output = new char [Length+1];
 if( Length > 0 )
 { strcpy( Output , pElem->GetText() ); }
 else
 { Output[0] = '\0'; }
 
 return Output;
}

bool GetBoolChildElement( TiXmlElement* Root, const char* ElementName )
{
 char* szTempText = GetStringChildElement( Root, ElementName );
 bool Output = false;
 if( szTempText[0] == 't' || szTempText[0] == 'T' || szTempText[0] == '1' )
 { Output = true; }
 delete [] szTempText;
 
 return Output;
}
